﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.DataProvider.Entites;
using IGM.Framework.Commons;
using IGM.Presentation.IgmServiceReference;
using IGM.Framework.Constants;

namespace IGM.Presentation.Materials
{
    public partial class LecturersControl : UserControl
    {
        private readonly DomainServiceClient _domainServiceClient;

         #region Constructor and Load Data

        public LecturersControl()
        {
            InitializeComponent();

            _domainServiceClient = new DomainServiceClient();
        }

        private void LecturersControlLoad(object sender, EventArgs e)
        {
            LoadMajors();
            Dock = DockStyle.Top;
        }

        private void LoadMajors()
        {
            cboMajors.DataSource = _domainServiceClient.GetMajors().Cast<Major>().ToList();
            cboMajors.DisplayMember = "Name";
            cboMajors.ValueMember = "Id";
        }

        private void LoadLecturers()
        {
            if (cboMajors.Items.Count > 0)
            {
                dgvLecturers.DataSource =
                    _domainServiceClient.GetLecturersByMajorId(((Major)cboMajors.SelectedItem).Id).Cast<Lecturer>().
                        ToList();

                DataGridViewHelper.ShowHideColumns(dgvLecturers, new[]
                                                                   {
                                                                       (string) typeof (Lecturer).Properties().IsChecked,
                                                                       (string) typeof (Lecturer).Properties().Name,
                                                                        "IdMajor", "DateOfBirth", "UniversityDegree"
                                                                   });
                DataGridViewHelper.ShowIsCheck(dgvLecturers);
                DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvLecturers, false);
                DataGridViewHelper.ChangeDgvHeaderText(dgvLecturers, new[] { "IsChecked", "Name", "IdMajor", "DateOfBirth", "UniversityDegree" },
                                                                     new[] { "Chọn", "Họ và tên", "Ngành", "Ngày tháng năm sinh", "Học vị"});
                LecturerCurrentRowChanged();
            }
            else
                MessageBox.Show(ConstantMessages.CanNotFindItem, @"ngành");
        }

        private void LecturerCurrentRowChanged()
        {
            if (dgvLecturers.CurrentRow != null)
            {
                txtName.Text = dgvLecturers.CurrentRow.Cells["Name"].Value.ToString();
                dtpBirthday.Value = (DateTime) dgvLecturers.CurrentRow.Cells["DateOfBirth"].Value;
                cboUniversityDegree.Text = dgvLecturers.CurrentRow.Cells["UniversityDegree"].Value.ToString();
            }

            else
            {
                txtName.Text = string.Empty;              
                ckbAllLecturers.Checked = false;
                dtpBirthday.Value = DateTime.Now;
                cboUniversityDegree.Text = string.Empty;
            }
        }
        private void CboMajorsSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadLecturers();
        }        

        private void DgvLecturersCurrentCellChanged(object sender, EventArgs e)
        {
            LecturerCurrentRowChanged();
        }

        private void DgvLecturersCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvLecturers == null ||
               dgvLecturers.Columns[(string)typeof(Lecturer).Properties().IsChecked] == null ||
               dgvLecturers.Columns[(string)typeof(Lecturer).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvLecturers[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvLecturers[e.ColumnIndex, e.RowIndex].Value;

            ckbAllLecturers.Checked = DataGridViewHelper.AllRowsIsCheck(dgvLecturers);
        }

        private void CkbAllLecturersCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvLecturers, ckbAllLecturers.Checked);
        }

        private void ReloadLecturers(string stundentName)
        {
            LoadLecturers();
            DataGridViewHelper.SetDgvCurrentCell(dgvLecturers, stundentName);
            LecturerCurrentRowChanged();
        }

        #endregion

        #region -- Add, Edit and Delete --
        private void BtnAddLecturersClick(object sender, EventArgs e)
        {
            try
            {
                var lecturer = new Lecturer
                                   {
                                       IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                                       Name = txtName.Text.Trim(),
                                       DateOfBirth = dtpBirthday.Value,
                                       UniversityDegree = cboUniversityDegree.SelectedItem.ToString()
                                   };
                string message;

                //if (_serviceClient.InsertLecturersValidator(lecturer, out message))
                //{
                //    _serviceClient.InsertLecturers(lecturer);

                //    ReloadLecturers(lecturer.Name);
                //}
                //else
                //    MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnEditLecturersClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvLecturers.CurrentRow != null)
                {
                    var lecturer = new Lecturer
                    {
                        Id = Convert.ToInt32(dgvLecturers.CurrentRow.Cells[(string)typeof(Lecturer).Properties().Id].Value),
                        Name = txtName.Text.Trim()
                    };
                    string message;

                    //if (_serviceClient.UpdateLecturerValidator(lecturer, out message))
                    //{
                    //    if (!_serviceClient.UpdateLecturers(lecturer))
                    //    {
                    //        MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                    //        return;
                    //    }
                    //    ReloadLecturers(lecturer.Name);
                    //}
                    //else
                    //    MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteLecturersClick(object sender, EventArgs e)
        {
            try
            {
                var lecturers = new List<Lecturer>();
                string message;

                for (var i = 0; i < dgvLecturers.RowCount; i++)
                {
                    if (!(bool)dgvLecturers[(string)typeof(Lecturer).Properties().IsChecked, i].Value) continue;

                    lecturers.Add(new Lecturer
                    {
                        Id = (int)dgvLecturers[(string)typeof(Lecturer).Properties().Id, i].Value,
                        Name = dgvLecturers[(string)typeof(Lecturer).Properties().Name, i].Value.ToString()
                    });
                }

                if (lecturers.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                //if (_serviceClient.DeleteLecturersValidator(faculties, out message))
                //{
                //    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các giảng viên đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                //    {
                //        _serviceClient.DeleteLecturers(lecturers);
                //        ReloadLecturers(null);
                //    }
                //}
                //else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }
        #endregion
    }
}
